import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lanouhn on 17/7/18.
 */
public class main {
    public static void main(String[] args){
        // java的网络请求
        // 网络连接对象
        HttpURLConnection connection = null;
        InputStream is = null; // 输入流，接收网络请求结果
        try {
            // 1.处理网址URL
            String myUrl = "https://cn.bing.com/az/hprichbg/rb/GeladaSimien_ZH-CN8344110980_1920x1080.jpg";
            // 改错快捷键 alt + enter
            URL url = new URL(myUrl);
            // 2.通过网址打开网络连接
            connection = (HttpURLConnection)url.openConnection();
            // 判断网络响应
            int code = connection.getResponseCode();
            if(code == 200){

                is = connection.getInputStream();
                byte[] bs = new byte[1024];
                int len;
                File sf = new File("/Users/lanouhn/Desktop/");
                OutputStream os = new FileOutputStream(sf.getPath() +"/"+"1.jpg");
                while ((len = is.read(bs)) != -1){
                    os.write(bs, 0, len);
                }
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        } finally {
            // 网络请求结果，及时的关流，断网，防止流量浪费
            // 防止网络长期保持连接不安全
            if (connection != null){
                connection.disconnect();
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
